package com.example.bawolf.thread;

import java.time.LocalDateTime;
import java.util.concurrent.CountDownLatch;
import java.util.stream.IntStream;

/**
 * @author zhougf
 * @version 1.0
 * @date 2020/06/09
 */
public class CountDownLatchTest {

    private static final CountDownLatch COUNT_DOWN_LATCH = new CountDownLatch(2);

    public static void main(String[] args) throws Exception{
        //第一种方式start
//        System.out.println(LocalDateTime.now() + "\t" + Thread.currentThread().getName() + "\ttrunning...");
//        Thread thread = getThread();
//        Thread thread2 = getThread();
//        thread.start();
//        thread2.start();
//        IntStream.range(0, 10).forEach(i -> {
//        System.out.println(LocalDateTime.now() + "\t" + Thread.currentThread().getName() + "\ti=" + i);
//        });
        //第一种方式end
        //join方式start
//        System.out.println(LocalDateTime.now() + "\t" + Thread.currentThread().getName() + "\ttrunning...");
//        Thread threadA = getThread();
//        threadA.setName("thread-A");
//        Thread threadB = new Thread(() -> {
//            threadA.start();
//            try {
//                threadA.join();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            System.out.println(LocalDateTime.now() + "\t" + Thread.currentThread().getName() + "\ttrunning...");
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            System.out.println(LocalDateTime.now() + "\t" + Thread.currentThread().getName() + "\tover...");
//        }, "Thread-B");
//
//            threadB.start();
//            //B先于main线程执行
//            threadB.join();
//                IntStream.range(0, 10).forEach(i -> {
//        System.out.println(LocalDateTime.now() + "\t" + Thread.currentThread().getName() + "\ti=" + i);
//        });
        //join方式end
                System.out.println(LocalDateTime.now() + "\t" + Thread.currentThread().getName() + "\ttrunning...");
        Thread thread = getThread();
        Thread thread2 = getThread();
        thread.start();
        thread2.start();
        COUNT_DOWN_LATCH.await();
        IntStream.range(0, 10).forEach(i -> {
        System.out.println(LocalDateTime.now() + "\t" + Thread.currentThread().getName() + "\ti=" + i);
        });

    }

    private static Thread getThread() {
        Thread thread = new Thread(() -> {
            System.out.println(LocalDateTime.now() + "\t" + Thread.currentThread().getName() + "\ttrunning...");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(LocalDateTime.now() + "\t" + Thread.currentThread().getName() + "\tover...");
            COUNT_DOWN_LATCH.countDown();
        });
     return thread;
    }
}
